<template>
    <FormProvider :form="form">
      <SchemaField>
        <SchemaArrayField name="custom" x-component="ArrayItems">
          <SchemaObjectField>
            <SchemaStringField name="input" x-component="Input" />
          </SchemaObjectField>
        </SchemaArrayField>
      </SchemaField>
    </FormProvider>
  </template>
  
  <script setup>
  import { ref } from 'vue';
  import { h } from 'vue';
  import { Input, Button, Space } from 'ant-design-vue';
  import { createForm } from '@formily/core';
  import {
    FormProvider,
    createSchemaField,
    RecursionField,
    useField,
    useFieldSchema,
  } from '@formily/vue';
  import 'ant-design-vue/dist/antd.css';
  
  // 定义 ArrayItems 组件
  const ArrayItems = () => {
    const field = useField();
    const schema = useFieldSchema();
  
    // 检查 field.value 是否为数组，如果不是则初始化为空数组
    const validValue = Array.isArray(field.value?.value) ? field.value.value : [];
  
    const items = validValue.map((item, index) => {
      return h('div', { key: item.id, style: { marginBottom: '10px' } }, [
        h(Space, [
          h(RecursionField, {
            props: { schema: schema.items, name: index },
          }),
          h(Input),
          h(Button, { onClick: () => field.value.remove(index) }, 'Remove'),
        ]),
      ]);
    });
    const button = h(
      Button,
      { 
        onClick: () => {
          if (field.value && typeof field.value.push === 'function') {
            field.value.push({ id: Date.now() });
          } else {
            console.error('field 没有 push 方法:', field);
          }
        } 
      },
      'Add'
    );
    return h('div', [items, button]);
  };
  
  const { SchemaField, SchemaStringField, SchemaArrayField, SchemaObjectField } =
    createSchemaField({
      components: {
        ArrayItems,
        Input,
      },
    });
  
  // 初始化表单时设置初始值为数组
  const form = ref(createForm({
    values: {
      custom: []
    }
  }));
  </script>